#include "total.h"

volatile uint8_t g_UART0_Receive_Data[10];           //UART0接收数据储存
volatile uint8_t g_UART0_Receive_Data_Hex[5];        //UART0接收数据数字部分原始十六进制存储
volatile float g_UART0_Receive_Data_Float;           //UART0接收数据数字部分转换为浮点数存储
volatile bool UART0_received = false;               //UART0接收完成标志位                              

/**
  * @brief  UART0事件处理函数，验证数据有效性并进行数据处理
  * @param  无
  * @retval 无
  */
void com_UART0Receive_Handle(void)
{
    if(UART0_received == true)
    {
        com_Byte_to_Float(&g_UART0_Receive_Data_Float, g_UART0_Receive_Data_Hex);
        com_MotorSpeed_PID_Set();
        UART0_received = false;
    }
}


/**
  * @brief  UART0通信进行电机速度PID设置
  * @param  无
  * @retval 无
  */
void com_MotorSpeed_PID_Set(void)
{
    if(g_UART0_Receive_Data_Hex[4] == 0x55)
    {
        hPosition_PID.Ki = g_UART0_Receive_Data_Float;
        // hPosition_PID.Setpoint = g_UART0_Receive_Data_Float;
        printf("_________________OK____________________\r\n");
    }
    else if(g_UART0_Receive_Data_Hex[4] == 0xA9)
    {
        hAngle_PID.Kp = g_UART0_Receive_Data_Float;
        // hPosition_PID.Kp = g_UART0_Receive_Data_Float;
        printf("_________________OK____________________\r\n");
    }
    else if(g_UART0_Receive_Data_Hex[4] == 0xA6)
    {
        hAngle_PID.Ki = g_UART0_Receive_Data_Float;
        // hPosition_PID.Ki = g_UART0_Receive_Data_Float;
        printf("_________________OK____________________\r\n");
    }
    else if(g_UART0_Receive_Data_Hex[4] == 0xA5)
    {
        // hAngle_PID.Kd = g_UART0_Receive_Data_Float;
        hPosition_PID.Kp = g_UART0_Receive_Data_Float;
        printf("_________________OK____________________\r\n");
    }
    else if(g_UART0_Receive_Data_Hex[4] == 0xB9)
    {
        Car_Base_Speed = g_UART0_Receive_Data_Float;
        printf("_________________OK____________________\r\n");
    }
    else if(g_UART0_Receive_Data_Hex[4] == 0xB6)
    {
        printf("_________________OK____________________\r\n");
    }
    else if(g_UART0_Receive_Data_Hex[4] == 0xB5)
    {
        hPosition_PID.Kd = g_UART0_Receive_Data_Float;
        printf("_________________OK____________________\r\n");
    }
}


/**
  * @brief  十六进制数转浮点数
  * @param  *f：转换完成的浮点数据储存地址  byte[]：要转换的字节数组
  * @retval 无
  */
void com_Byte_to_Float(float *f,unsigned char byte[])
{
	FloatLongType fl;
	fl.ldata=0;
	fl.ldata=byte[3];
	fl.ldata=(fl.ldata<<8)|byte[2];
	fl.ldata=(fl.ldata<<8)|byte[1];
	fl.ldata=(fl.ldata<<8)|byte[0];
	*f=fl.fdata;
}


/*串口printf重定向*/
int fputc(int c, FILE* stream)
{
    DL_UART_Main_transmitDataBlocking(UART_0_INST, c);
    return c;
}

int fputs(const char* restrict s, FILE* restrict stream)
{
    uint16_t i, len;
    len = strlen(s);
    for(i=0; i<len; i++)
    {
        DL_UART_Main_transmitDataBlocking(UART_0_INST, s[i]);
    }
    return len;
}

int puts(const char *_ptr)
{
    int count = fputs(_ptr, stdout);
    count += fputs("\n", stdout);
    return count;
}
